package me.jiatao.wan.di

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import me.jiatao.wan.AppConfig
import me.jiatao.wan.BuildConfig
import me.jiatao.wan.data.network.api.WanAndroidApi
import me.jiatao.wan.data.network.okhttp3.CustomCookieJar
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

/**
 * @Author: taojia
 * @CreateDate: 2021/8/24 3:40 下午
 * @Version: 1.0
 * @Description: 提供全局网络相关单例对象
 */

@Module
@InstallIn(SingletonComponent::class)
object NetWorkModule {

    /**
     * Provides 常用于被 @Module 注解标记类的内部的方法，并提供依赖项对象。
     *
     * Singleton 提供单例
     */

    @Provides
    @Singleton
    fun provideLoggingInterceptor(): HttpLoggingInterceptor {
        /**
         * 日志拦截器
         */
        val loggingInterceptor = HttpLoggingInterceptor()
        // 包含header、body数据
        if (BuildConfig.DEBUG) {
            loggingInterceptor.level = HttpLoggingInterceptor.Level.HEADERS
        } else {
            loggingInterceptor.level = HttpLoggingInterceptor.Level.NONE
        }
        return loggingInterceptor;
    }

    @Provides
    @Singleton
    fun provideOkHttpClient(loggingInterceptor: HttpLoggingInterceptor): OkHttpClient {
        /**
         * Header拦截器
         */
        val headerInterceptor = Interceptor { chain ->
            val request = chain.request()
                .newBuilder()
                .addHeader("Content_Type", "application/json")
                .addHeader("charset", "UTF-8")
                .build()

            chain.proceed(request)
        }

        return OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS) //设置超时时间
            .readTimeout(10, TimeUnit.SECONDS) //设置读取超时时间
            .writeTimeout(10, TimeUnit.SECONDS)
            .addInterceptor(loggingInterceptor)
            .addInterceptor(headerInterceptor)
            .cookieJar(CustomCookieJar())
            .build()
    }

    @Provides
    @Singleton
    fun provideGson(): Gson {
        return GsonBuilder()
            .serializeNulls()
            .create()
    }

    @Provides
    @Singleton
    fun provideRetrofit(okHttpClient: OkHttpClient, gson: Gson): Retrofit {
        return Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl(AppConfig.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
    }

    @Provides
    @Singleton
    fun provideWanService(retrofit: Retrofit): WanAndroidApi {
        return retrofit.create(WanAndroidApi::class.java)
    }
}
